using System;
using System.Collections.Generic;
using Google.Protobuf;
using UnityEngine;
using UnityEngine.Networking;
using MyFramework.Resource;
using MyFramework.Singleton;

namespace MyFramework.Network
{
    public class NetworkManager : Singleton<NetworkManager>
    {
        public readonly NetworkConfig Config =
            ResourcesManager.GetInstance().Load<NetworkConfig>("config/NetworkConfig");

        public async void Get(string url, INetworkHandler handler)
        {
            try
            {
                UnityWebRequest request = UnityWebRequest.Get(url);
                await request.SendWebRequest().Await();

                if (request.result == UnityWebRequest.Result.Success)
                    handler?.OnSuccess(request.downloadHandler.data);
                else
                    handler?.OnFailure(request.error);
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }
        }

        public async void Post(string url, IMessage protobufData, INetworkHandler handler)
        {
            try
            {
                byte[] data = protobufData.ToByteArray();
            
                UnityWebRequest request = new UnityWebRequest(url, "POST");
                request.uploadHandler = new UploadHandlerRaw(data);
                request.downloadHandler = new DownloadHandlerBuffer();
                request.SetRequestHeader("Content-Type", "application/x-protobuf");
            
                await request.SendWebRequest().Await();

                if (request.result == UnityWebRequest.Result.Success)
                    handler?.OnSuccess(request.downloadHandler.data);
                else
                    handler?.OnFailure(request.error);
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
    }
}